<?php

namespace yphp;
/**
 * Class View
 * @package yphp
 * 视图类
 */
class Template extends Compile
{

    // 子视图路由加密
    protected $lock;

    // 模板对象
    function construct($names, $lock, $change)
    {
        $this->lock = $lock;
        $this->path = $this->changePath($names);
        $this->view_path = $this->getview($this->path);
        if (!is_file($this->view_path)) throw new \Exception('找不到视图：' . $names);
        $this->compile_path = $this->getCompile($this->path);
        if (!$this->isCompileUse($this->compile_path, $this->view_path) || file_get_contents($this->compile_path, false, null, 8, strlen($change)) !== $change) {
            DealFile::writeFile($this->compile_path, "<?php /*$change*/ ?>" . $this->compile($this->section($change)), true);
            DealFile::delDir(CACHE_HTML_PATH . $this->path . DS . $this->lock, true);
        }
    }

 
    // 重写区块
    function section($change)
    {
        $change = unserialize(base64_decode($change));
        return preg_replace_callback('/<show\s*name=([\'"])(.+?)\1\s*>(.*?)<\/show>/us', function ($match) use (&$change) {
            return key_exists($match[2], $change) ? str_replace('<parent/>', $match[3], $change[$match[2]]) : $match[3];
        }, file_get_contents($this->view_path));
    }

    // 获取编译文件路径
    protected function getCompile($path)
    {
        return CACHE_COMPILE_PATH . $path . DS . $this->lock . '.html';
    }
 
    // 获取静态文件路径
    protected function getHtml($path)
    {
        return CACHE_HTML_PATH . $path . DS . $this->lock . DS . Safe::en(serialize(Request::instance()->path())) . '.html';
    }

}